local hx__cqbd = fk.CreateSkill{
  name = "hx__cqbd",
}


local HX = require "packages/huixiangkill/hxfs"

hx__cqbd:addEffect(fk.GameStart, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(hx__cqbd.name)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(player.room.alive_players) do
      local p_num = p:getHandcardNum()
      room:setPlayerMark(p, "@hx__cqbd_record", {p.hp, p_num})
    end
  end,
})

hx__cqbd:addEffect(fk.TurnStart, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(hx__cqbd.name)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(player.room.alive_players) do
      local p_num = p:getHandcardNum()
      room:setPlayerMark(p, "@hx__cqbd_record", {p.hp, p_num})
    end
  end,
})


hx__cqbd:addEffect(fk.TurnEnd, {
  anim_type = "control",
  can_trigger = function(self, event, target, player, data)
    return player:hasSkill(hx__cqbd.name)
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    for _, p in ipairs(player.room.alive_players) do
      local p_hp
      if p:getTableMark("@hx__cqbd_record")[1] ~= nil then
        p_hp = p:getTableMark("@hx__cqbd_record")[1]
      else
        p_hp = p.hp
      end
      local p_num
      if p:getTableMark("@hx__cqbd_record")[2] ~= nil then
        p_num = p:getTableMark("@hx__cqbd_record")[2]
      else
        p_num = p:getHandcardNum()
      end
      room:setPlayerProperty(p, "hp", p_hp)
      HX.SetPlayerHandNum(room, p, p_num, hx__cqbd.name)
      HX.SetSkillsTimes(room,p,0)
    end
  end,
})


hx__cqbd:addEffect(fk.AskForPeachesDone, {
  mute = true,
  is_delay_effect = true,
  can_trigger = function(self, event, target, player, data)
    return target == player and player:hasSkill(hx__cqbd.name, true) and player.hp <= 0
  end,
  on_use = function(self, event, target, player, data)
    local room = player.room
    room:notifySkillInvoked(player,"hx__cqbd","big")
    for _, p in ipairs(player.room.alive_players) do
      local p_hp
      if p:getTableMark("@hx__cqbd_record")[1] ~= nil then
        p_hp = p:getTableMark("@hx__cqbd_record")[1]
      else
        p_hp = p.hp
      end
      local p_num
      if p:getTableMark("@hx__cqbd_record")[2] ~= nil then
        p_num = p:getTableMark("@hx__cqbd_record")[2]
      else
        p_num = p:getHandcardNum()
      end
      room:setPlayerProperty(p, "hp", p_hp)
      HX.SetPlayerHandNum(room, p, p_num, hx__cqbd.name)
      HX.SetSkillsTimes(room,p,0)
    end
    player:gainAnExtraTurn()
    room:handleAddLoseSkills(player, "-hx__cqbd")
  end,
})

return hx__cqbd